package com.zjinyin.forum.service.impl;

import com.zjinyin.forum.common.AppResult;
import com.zjinyin.forum.common.ResultCode;
import com.zjinyin.forum.dao.ArticleMapper;
import com.zjinyin.forum.exception.ApplicationException;
import com.zjinyin.forum.model.Article;
import com.zjinyin.forum.model.Board;
import com.zjinyin.forum.model.User;
import com.zjinyin.forum.service.IArticleService;
import com.zjinyin.forum.service.IBoardService;
import com.zjinyin.forum.service.IUserService;
import com.zjinyin.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2023-08-10
 * Time: 15:06
 */

/**
 * 针对文章相关接口功能的具体实现
 */
@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Resource
    private ArticleMapper articleMapper;

    /**
     * TODO : 当 ArticleServiceImpl 中需要引用下面这两个 service 层里的方法,
     *        那么这两个层里面就不能再引用 articleService, 否则构成循环引用,
     *        再加载注入的时候不知道先注入下面两个 service 还是 articleService
     *        可以进行注入 mapper, 在 mapper 中实现所需要的方法
     */
    @Resource
    private IUserService userService;

    @Resource
    private IBoardService boardService;


    /**
     * 用户发表一篇帖子 -- 设计那个版块 那个用户
     *
     * @param article 帖子
     */
    @Override
    public void create(Article article) {
        // 1. 校验参数
        if (article == null || article.getUserId() == null || article.getBoardId() == null ||
                StringUtil.isEmpty(article.getTitle()) || StringUtil.isEmpty(article.getContent())) {
            log.warn("新增文章失败 : " + ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 2. 设置默认值, 减少数据库操作压力
        // 2.1 帖子访问数
        article.setVisitCount(0);
        // 2.2 帖子回复数
        article.setReplyCount(0);
        // 2.3 帖子点赞数
        article.setLikeCount(0);
        // 2.4 帖子状态
        article.setState((byte) 0);
        // 2.5 帖子是否删除
        article.setDeleteState((byte) 0);
        // 2.6 帖子创建和更新时间
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);

        // 3. 插入数据库文章表 -- 动态插入文章
        int row = articleMapper.insertSelective(article);

        // 4. 校验 row
        if (row != 1) {
            log.warn(ResultCode.FAILED_CREATE.toString() + ", 受影响行数不为 1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        // 5. 更新发表用户的文章数
        User user = userService.selectByPrimaryKey(article.getUserId());
        if (user == null) {
            log.warn("user id : " + article.getUserId() + " " + ResultCode.FAILED_CREATE.toString() + ", 用户更新文章数异常");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        userService.increaseOneArticleCountById(user.getId());

        // 6. 更新指定版块文章总数
        Board board = boardService.selectById(article.getBoardId());
        // 版块不存在
        if (board == null) {
            log.warn("board id : " + article.getBoardId() + " " + ResultCode.FAILED_CREATE.toString() + ", 版块不存在");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        boardService.increaseOneArticleCountById(board.getId());
        log.info(ResultCode.SUCCESS + " user id : " + user.getId() +
                ", board id : " + board.getId() + ", article id : " + article.getId() + " 帖子发布成功");

    }

    /**
     * 查询所有未被删除的帖子集合
     *
     * @return 帖子集合
     */
    @Override
    public List<Article> selectAll() {
        return articleMapper.selectAll();
    }


    /**
     * 根据版块 Id 查询对应版块下的所有未删除的帖子
     *
     * @param boardId 版块 Id
     * @return 返回指定板块下的帖子对象集合
     */
    @Override
    public List<Article> selectArticleByBoardId(Long boardId) {
        // 1. 参数校验
        if (boardId == null || boardId <= 0) {
            log.warn("boardId : " + boardId + " " + ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 2. 检验是否存在该版块 -- 先检验 boardId 是否存在, 不存在就不连表查询, 减少数据库压力
        Board board = boardService.selectById(boardId);
        if (board == null) {
            log.warn("boardId : " + boardId + " " + ResultCode.FAILED_BOARD_NOT_EXISTS.toString() + ", 没有对应文章资源");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }

        // 3. 获取指定 boardId 的所有文章
        List<Article> list = articleMapper.selectArticleByBoardId(boardId);

        // list 不存在交给前端校验
        log.info("查询到 boardId : " + boardId + " 下的文章");

        return list;
    }


    /**
     * 根据帖子 id 多表联查指定帖子
     *
     * @param id 帖子 id
     * @return 返回指定帖子对象
     */
    @Override
    public Article selectArticleByABoardIdAndAId(Long id) {
        // 1. 校验参数
        if (id == null || id <= 0) {
            log.warn("ArticleId : " + id + " " + ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 2. 查询指定帖子对象
        Article article = articleMapper.selectArticleByABoardIdAndAId(id);

        // 3. 检验集合
        if (article == null) {
            log.warn("ArticleId : " + id + " " + ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        // 4. 点击这个帖子后 需要给访问数 + 1
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount() + 1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);

        // 5. 检验 row
        if (row != 1) {
            log.warn("ArticleId : " + id + " " + ResultCode.ERROR_SERVICES.toString() + ", 浏览数更新失败");
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

        // TODO : 由于是新构建的 updateArticle 进行更新浏览数, 但已经提前查询了 Article, 里面的浏览数还是未更新前的
        //        需要主动进行返回浏览数的更新
        article.setVisitCount(article.getVisitCount() + 1);

        // 返回查询指定帖子
        return article;
    }


    /**
     * 修改指定帖子
     *
     * @param id      帖子 id
     * @param title   帖子标题
     * @param content 帖子正文
     */
    @Override
    public void modify(Long id, String title, String content) {
        // 1. 校验参数
        if (id == null || id <= 0 || StringUtil.isEmpty(title) || StringUtil.isEmpty(content)) {
            log.warn("ArticleId : " + id + " " + ResultCode.FAILED_PARAMS_VALIDATE);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 2. 构建新文章对象
        Article updateArticle = new Article();
        // 2.1 指定id
        updateArticle.setId(id);
        // 2.2 更新标题
        updateArticle.setTitle(title);
        // 2.3 更新正文
        updateArticle.setContent(content);
        // 2.4 更新时间
        updateArticle.setUpdateTime(new Date());

        // 3. 写回数据库
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);

        // 4. 检验是否整个写入
        if (row != 1) {
            log.warn("ArticleId : " + id + " " + ResultCode.FAILED_USER_COUNT_ARTICLE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_COUNT_ARTICLE));
        }

        log.info("Article : " + id + ", 帖子标题正文等更新成功");

    }


    /**
     * 根据制定 id
     *
     * @param id 帖子 id
     */
    @Override
    public Article selectById(Long id) {
        // 1. 参数校验
        if (id == null || id <= 0) {
            log.warn("Article id : " + id + " " + ResultCode.FAILED_PARAMS_VALIDATE);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 2. 根据 id 动态查询帖子
        Article article = articleMapper.selectByPrimaryKey(id);

        if (article == null) {
            log.warn("Article id : " + id + " " + ResultCode.FAILED_ARTICLE_NOT_EXISTS);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        return article;
    }

    /**
     * 实现点赞后帖子的点赞数 + 1
     *
     * @param id 帖子 id
     */
    @Override
    public void chickLikeCount(Long id) {
        // 1. 参数校验
        if (id == null || id <= 0) {
            log.warn("Article id : " + id + " " + ResultCode.FAILED_PARAMS_VALIDATE);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 2. 获取指定 id 帖子
        Article article = articleMapper.selectByPrimaryKey(id);

        // 帖子不存在
        if (article == null) {
            log.warn("Article id : " + id + " " + ResultCode.FAILED_ARTICLE_NOT_EXISTS);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        // 帖子状态异常
        if (article.getState() == 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_ABNORMAL));
        }

        // 帖子已经删除
        if (article.getDeleteState() == 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        // 3. 创建新帖
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setLikeCount(article.getLikeCount() + 1);
        updateArticle.setUpdateTime(new Date());

        // 更新这个帖子
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);

        // 检验结果
        if (row != 1) {
            log.warn("Article id : " + id + " " + ResultCode.ERROR_SERVICES + ", 更新点赞数错误");
        }

        log.info("点赞成功!");
    }


    /**
     * 删除指定帖子
     *
     * @param id 帖子 id
     */
    @Override
    public void deleteById(Long id) {
        // 1. 参数校验
        if (id == null || id <= 0) {
            log.warn("Article id : " + id + " " + ResultCode.FAILED_PARAMS_VALIDATE);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 2. 根据 id 查询帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);

        // 3. 检验结果
        if (article == null || article.getDeleteState() == 1) {
            log.warn("ArticleId : " + id + " " + ResultCode.FAILED_ARTICLE_NOT_EXISTS);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        // 4. 创建更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);

        // 5. 执行更新, 修改删除状态并不实际删除文章, 利于用户找回数据
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);

        // 6. 检验结果
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES + " , 受影响行数不为 1 错误");
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES) + " , 受影响行数不为 1 错误");
        }

        // 7. 更新板块数, 用户发帖数
        boardService.deleteOneArticleCountById(article.getBoardId());
        userService.deleteOneArticleCountById(article.getUserId());

        log.info("成功删除当前文章, " + "userId : " + article.getUserId() + ", boardId : " + article.getBoardId());
    }


    /**
     * 回复帖子数加 + 1
     *
     * @param id 帖子 id
     */
    @Override
    public void addOneReplyCountById(Long id) {
        // 1. 参数校验
        if (id == null || id <= 0) {
            log.warn("Article id : " + id + " " + ResultCode.FAILED_PARAMS_VALIDATE);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 2. 根据 id 查询帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);

        // 3. 检验结果
        if (article == null || article.getDeleteState() == 1) {
            log.warn("ArticleId : " + id + " " + ResultCode.FAILED_ARTICLE_NOT_EXISTS);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        // 帖子封铁 不允许在回复
        if (article.getState() == 1) {
            log.warn("ArticleId : " + id + " " + ResultCode.FAILED_ARTICLE_ABNORMAL);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_ABNORMAL));

        }

        // 4. 创建更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setReplyCount(article.getReplyCount() + 1);

        // 5. 执行更新
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);

        // 6. 检验结果
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES + " , 受影响行数不为 1 错误");
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES) + " , 受影响行数不为 1 错误");
        }

        log.info("更新回复数成功, " + "userId : " + article.getUserId() + ", articleId : " + article.getId());

    }


    /**
     * 根据用户 id 多表联查文章和版块表中, 指定用户的所有为删除文章的信息
     *
     * @param userId 用户 id
     */
    @Override
    public List<Article> selectArticleByUserId(Long userId) {

        // 1. 参数检验
        if (userId == null || userId <= 0) {
            log.warn("userId : " + userId + " " + ResultCode.FAILED_PARAMS_VALIDATE);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 2. 查询指定 id 用户
        User user = userService.selectByPrimaryKey(userId);
        if (user == null) {
            log.warn("userId : " + userId + " " + ResultCode.FAILED_USER_NOT_EXISTS);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        // 3. 查询指定 userId 的文章
        List<Article> list = articleMapper.selectArticleByUserId(userId);

        if (list == null) {
            list = new ArrayList<>();
        }

        return list;
    }


    /**
     * 根据标题关键字模糊匹配文章
     *
     * @param title 文章标题关键字
     */
    @Override
    public List<Article> selectAllArticleByTitle(String title) {
        // 1. 参数校验
        if (StringUtil.isEmpty(title)) {
            log.warn("title : " + ResultCode.FAILED_PARAMS_VALIDATE);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED + " 请输入要搜索的内容"));
        }

        // 2. 按照标题关键字查询文章
        List<Article> list = articleMapper.selectAllArticleByTitle(title);

        if (list == null) {
            list = new ArrayList<>();
        }

        return list;
    }
}
